package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.rmi.MarshalledObject;

/**
 * 登录 认证类
 * @author 20201115
 */
@Controller
@RequestMapping("/login")
public class AuthController {


    private AuthService authService;
    @Autowired
    public AuthController(AuthService authService){
        this.authService = authService;
    }
    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;


    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(name = "FROM", required = false, defaultValue = "") String from, Model model){
        model.addAttribute("from",from);
        return "login";
    }


    /**
     * 首先，在 过滤器方法中，将 此登录信息的请求路径，进行过滤，不拦截
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response){
        //1 校验 用户名，密码 是否为空
        if (username == null){
            throw new RuntimeException("输入的用户名 为空!");
        }
        if (password == null){
            throw new RuntimeException("输入的密码 为空!");
        }
        //2 进行 令牌信息的获取
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //3  将 令牌信息的 jti 存入 cookie中
        this.setJtiToCookie(authToken.getJti(), response);

        //4 返回 结果信息
        return new Result(true, StatusCode.OK,"登录成功",authToken.getJti());
    }

    /**
     * 将 令牌的短标识jti 存入到cookie中
     * @param jti
     */
    private void setJtiToCookie(String jti, HttpServletResponse response) {
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }


}
